import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx'
import { Browser, BrowserHrm, Upload } from 'weaver-mobile-page'
import { withRouter } from 'react-router-dom';
import { Tools, List } from 'weaver-mobile';
import FoldList from '../../../../public/foldlist'
import * as TaskMainApis from '../../../../api/task/taskMain'
import * as Util from '../../../../util'

const FormItem = List.FormItem
const getLabel = Tools.getLabel

@inject("taskDetailRelateinfoStore", "taskDetailStore", "taskCommonStore")
@withRouter
@observer
class Relateinfo extends React.Component {

    constructor(props) {
        super(props)
        this.state = { ...props, needSticky: true }
    }

    componentWillMount() {
        this.init(this.state.detail)

        const { changeCategory, changeMaxUploadSize } = this.props.taskDetailRelateinfoStore
        Tools.callApi({
            url: "/api/workrelate/task/getTaskFileCategory",
            method: "GET",
            params: {},
            type: "json"
        }).then((data) => {
            if (data.status == 1) {
                changeCategory(data.secId)
                changeMaxUploadSize(data.maxsize)
            }
        })
    }

    componentWillReceiveProps(newProps) {
        this.state.detail = newProps.detail
        this.init(this.state.detail)
    }

    componentWillUnmount() {

    }

    init = (detail) => {
        const { id, rtaskarry, goalarry, docarry, wfarry, crmarry, projectarry, filearry, asslist } = detail
        const { changeTaskid, changeGoalDatas, changeTaskDatas, changeDocDatas, changeProcessDatas, changeCustomerDatas,
            changeProjectDatas, changeFileDatas, changeConnectGoals, changeConnectTasks, changeConnectPlans } = this.props.taskDetailRelateinfoStore
        changeTaskid(id)
        changeTaskDatas(this.prehandleRelateDatas(rtaskarry, "taskids"))
        changeGoalDatas(this.prehandleRelateDatas(goalarry, "goalids"))
        changeDocDatas(this.prehandleRelateDatas(docarry, "docids"))
        changeProcessDatas(this.prehandleRelateDatas(wfarry, "wfids"))
        changeCustomerDatas(this.prehandleRelateDatas(crmarry, "crmids"))
        changeProjectDatas(this.prehandleRelateDatas(projectarry, "projectids"))
        changeFileDatas(this.prehandleRelateDatas(filearry, "fileids"))

        changeConnectTasks([])
        changeConnectGoals([])
        changeConnectPlans([])
        if (asslist && asslist.length > 0) {
            asslist.forEach((d, i) => {
                if (d.columninfo === "taskids") {
                    changeConnectTasks(this.prehandleRelateDatas(d.datas, "connectTaskids"))
                } else if (d.columninfo === "goalids") {
                    changeConnectGoals(this.prehandleRelateDatas(d.datas, "connectGoalids"))
                } else if (d.columninfo === "planids") {
                    changeConnectPlans(this.prehandleRelateDatas(d.datas, "connectPlanids"))
                }
            })
        }
    }

    prehandleRelateDatas = (datas, fieldname) => {
        const { canedit } = this.state.detail
        datas = datas || []
        let newDatas = []
        if (["goalids", "taskids", "docids", "wfids", "crmids", "projectids", "connectGoalids", "connectTaskids", "connectPlanids"].indexOf(fieldname) > -1) {
            datas.forEach((d, i) => {
                let data = { ...d }
                data.comsbtn = canedit ? [
                    {
                        text: getLabel(91, '删除'),
                        onPress: () => { this.onDataDelete(fieldname, d.id) },
                        style: { backgroundColor: "rgba(170, 170, 170, 1)", color: 'white', padding: "0 15px" }
                    }
                ] : []
                newDatas.push(data)
            })
        } else if (["fileids"].indexOf(fieldname) > -1) {
            datas.forEach((d, i) => {
                let data = { ...d }
                data.comsbtn = canedit ? [
                    {
                        text: getLabel(258, '下载'),
                        onPress: () => { this.onDataDownload(d.id, d.fileid) },
                        style: { backgroundColor: "rgba(77, 122, 216, 1)", color: 'white', padding: "0 15px" }
                    },
                    {
                        text: getLabel(91, '删除'),
                        onPress: () => { this.onDataDelete(fieldname, d.id) },
                        style: { backgroundColor: "rgba(170, 170, 170, 1)", color: 'white', padding: "0 15px" }
                    }
                ] : [
                        {
                            text: getLabel(258, '下载'),
                            onPress: () => { this.onDataDownload(d.id, d.fileid) },
                            style: { backgroundColor: "rgba(77, 122, 216, 1)", color: 'white', padding: "0 15px" }
                        }
                    ]
                newDatas.push(data)
            })
        }

        return newDatas
    }

    onDataDelete = (fieldname, deleteval) => {
        const { taskCommonStore } = this.props
        const { taskDetail, changeTaskDetail } = this.props.taskDetailStore
        const { taskid, taskDatas, goalDatas, docDatas, processDatas, customerDatas, projectDatas, fileDatas } = this.props.taskDetailRelateinfoStore
        let targetDatas = []
        if (fieldname === "taskids") {
            targetDatas = taskDatas
        } else if (fieldname === "goalids") {
            targetDatas = goalDatas
        } else if (fieldname === "docids") {
            targetDatas = docDatas
        } else if (fieldname === "wfids") {
            targetDatas = processDatas
        } else if (fieldname === "crmids") {
            targetDatas = customerDatas
        } else if (fieldname === "projectids") {
            targetDatas = processDatas
        } else if (fieldname === "fileids") {
            targetDatas = fileDatas
        }

        let fieldvalue = targetDatas.filter((d, i) => { return d.id != deleteval }).map((d, i) => { return d.id }).join(",")
        if (fieldvalue != "") {
            fieldvalue = "," + fieldvalue + ","
        }
        TaskMainApis.editTaskInfo({
            taskId: taskid,
            fieldname,
            fieldvalue: fieldname === "fileids" ? deleteval : fieldvalue,
            fieldtype: fieldname === "fileids" ? "del" : "str",
            delvalue: deleteval
        }).then(res => {
            if (res.status == "1") {
                taskCommonStore.deleteSuccess()
                fieldname === "goalids" && changeTaskDetail({ ...taskDetail, goalarry: taskDetail.goalarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "taskids" && changeTaskDetail({ ...taskDetail, rtaskarry: taskDetail.rtaskarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "docids" && changeTaskDetail({ ...taskDetail, docarry: taskDetail.docarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "wfids" && changeTaskDetail({ ...taskDetail, wfarry: taskDetail.wfarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "crmids" && changeTaskDetail({ ...taskDetail, crmarry: taskDetail.crmarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "projectids" && changeTaskDetail({ ...taskDetail, projectarry: taskDetail.projectarry.filter((d, i) => { return d.id != deleteval }) })
                fieldname === "fileids" && changeTaskDetail({ ...taskDetail, filearry: taskDetail.filearry.filter((d, i) => { return d.id != deleteval }) })
            }
        })
    }

    onDataDownload = (id, fileid) => {
        const { taskid } = this.props.taskDetailRelateinfoStore
        window.downloadFile(id, fileid, taskid, "2")
    }

    onRelateInfoChange = (taskid, fieldname, newDatas, fieldvalue) => {
        const { taskCommonStore } = this.props
        const { taskDetail, changeTaskDetail } = this.props.taskDetailStore

        const { goalDatas, taskDatas, docDatas, processDatas, customerDatas, projectDatas, fileDatas } = this.props.taskDetailRelateinfoStore

        let oldDatas = []
        if (fieldname === "goalids") {
            oldDatas = goalDatas
        } else if (fieldname === "taskids") {
            oldDatas = taskDatas
        } else if (fieldname === "docids") {
            oldDatas = docDatas
        } else if (fieldname === "wfids") {
            oldDatas = processDatas
        } else if (fieldname === "crmids") {
            oldDatas = customerDatas
        } else if (fieldname === "projectids") {
            oldDatas = projectDatas
        } else if (fieldname === "fileids") {
            oldDatas = fileDatas
        }

        let newIdsStr = newDatas.length > 0 ? "," + newDatas.map((d, i) => { return d.id }).join(",") + "," : ""
        let oldIdsStr = oldDatas.length > 0 ? "," + oldDatas.map((d, i) => { return d.id }).join(",") + "," : ""
        let logDelValue = Util.ArrayDiffer(oldIdsStr, newIdsStr, 1)
        let logAddValue = Util.ArrayDiffer(oldIdsStr, newIdsStr.split(","), 2)
        if (newIdsStr !== oldIdsStr) {
            TaskMainApis.editTaskInfo({
                taskId: taskid,
                fieldname,
                fieldvalue: fieldname != "fileids" ? newIdsStr : fieldvalue,
                fieldtype: "str",
                addvalue: logAddValue,
                delvalue: logDelValue
            }).then(res => {
                if (res.status === "1") {
                    if (fieldname !== "fileids") {
                        taskCommonStore.updateSuccess()
                    }
                    fieldname === "goalids" && changeTaskDetail({ ...taskDetail, goalarry: newDatas })
                    fieldname === "taskids" && changeTaskDetail({ ...taskDetail, rtaskarry: newDatas })
                    fieldname === "docids" && changeTaskDetail({ ...taskDetail, docarry: newDatas })
                    fieldname === "wfids" && changeTaskDetail({ ...taskDetail, wfarry: newDatas })
                    fieldname === "crmids" && changeTaskDetail({ ...taskDetail, crmarry: newDatas })
                    fieldname === "projectids" && changeTaskDetail({ ...taskDetail, projectarry: newDatas })
                    fieldname === "fileids" && changeTaskDetail({ ...taskDetail, filearry: newDatas })
                }
            })
        }
    }

    onUploadDatasChange = (datas) => {
        const { taskid } = this.props.taskDetailRelateinfoStore
        const { fileDatas, changeFileDatas } = this.props.taskDetailRelateinfoStore
        let newFileDatas = [...fileDatas]
        let fieldvalue = ""
        datas.forEach((data, i) => {
            if (newFileDatas.indexOf(data.id) == -1) {
                data.size = data.filesize
                data.fileid = data.imagefileid  // 重置fileid
                newFileDatas.push(data)
                fieldvalue = fieldvalue + data.id + ","
            }
        })
        this.onRelateInfoChange(taskid, "fileids", newFileDatas, fieldvalue)
    }

    render() {
        const { detail, needSticky } = this.state
        const { taskid, taskDetailRelateGoalBrowserStore, taskDetailRelateTaskBrowserStore, taskDetailRelateDocBrowserStore,
            taskDetailRelateProcessBrowserStore, taskDetailRelateCustomerBrowserStore, taskDetailRelateProjectBrowserStore,
            taskDetailRelateFileBrowserStore,
            goalDatas, taskDatas, docDatas, processDatas, customerDatas, projectDatas,
            goalFoldlistDatas, taskFoldlistDatas, docFoldlistDatas, processFoldlistDatas, customerFoldlistDatas,
            projectFoldlistDatas, fileFoldlistDatas, connectGoalsFoldListDatas, connectTasksFoldListDatas, connectPlansFoldListDatas,
            category, maxUploadSize } = this.props.taskDetailRelateinfoStore

        return (
            <div className="workrelate-mobile-task-relateinfo-wrapper">
                {/* {
                    detail.relateInfo.map((d, i) => {
                        return 
                    })
                } */}

                <FoldList
                    sticky={needSticky}
                    data={goalFoldlistDatas}
                    showseq={false}
                    headColor={"#96358A"}
                    headIconclass={"executive-force"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={goalFoldlistDatas.length}
                    title={getLabel(382586, '相关目标')}
                    open={true}
                    onItemClick={(dataid) => {
                        window.openAppLink(null, dataid, "wrlgoal", null, null)
                    }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateGoalBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={"wrlgoal"}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "goalids", toJS(arg[2]))
                                }}
                                valueArray={goalDatas}
                            />,
                            store: taskDetailRelateGoalBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={taskFoldlistDatas}
                    showseq={false}
                    headColor={"#1A57A0"}
                    headIconclass={"related-tasks"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={taskFoldlistDatas.length}
                    title={getLabel(33414, '相关任务')}
                    open={true}
                    onItemClick={(dataid) => {
                        // this.props.history.replace("/taskHome/taskDetail/" + dataid)
                        // changeTaskid(dataid)
                        // changeTaskDetail({})
                        window.openAppLink(null, dataid, "wrltask", null, null)
                    }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateTaskBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={"wrltsk"}
                                dataParams={{ parentid: -1 }}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "taskids", toJS(arg[2]))
                                }}
                                valueArray={taskDatas}
                            />,
                            store: taskDetailRelateTaskBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={docFoldlistDatas}
                    showseq={false}
                    headColor={"#F14A2D"}
                    headIconclass={"currency"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={docFoldlistDatas.length}
                    title={getLabel('857', '相关文档')}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 37, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateDocBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={37}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "docids", toJS(arg[2]))
                                }}
                                valueArray={docDatas}
                            />,
                            store: taskDetailRelateDocBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={processFoldlistDatas}
                    showseq={false}
                    headColor={"#2F4F4F"}
                    headIconclass={"process"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={processFoldlistDatas.length}
                    title={getLabel('22105', '相关流程')}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 152, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateProcessBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={152}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "wfids", toJS(arg[2]))
                                }}
                                valueArray={processDatas}
                            />,
                            store: taskDetailRelateProcessBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={customerFoldlistDatas}
                    showseq={false}
                    headColor={"#808000"}
                    headIconclass={"relevant-customer"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={customerFoldlistDatas.length}
                    title={getLabel('783', '相关客户')}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 7, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateCustomerBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={7}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "crmids", toJS(arg[2]))
                                }}
                                valueArray={customerDatas}
                            />,
                            store: taskDetailRelateCustomerBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={projectFoldlistDatas}
                    showseq={false}
                    headColor={"#6B8E23"}
                    headIconclass={"relevant-project"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={projectFoldlistDatas.length}
                    title={getLabel('782', '相关项目')}
                    open={true}
                    onItemClick={(dataid) => { window.openAppLink(null, dataid, 8, null, null) }}
                    itemBottomOffset={0}
                    addIconIsBrowser={true}
                    browser={
                        {
                            com: <Browser
                                store={taskDetailRelateProjectBrowserStore}
                                dataURL={"/api/public/browser/data/"}
                                isSingle={false}
                                type={8}
                                onChange={(...arg) => {
                                    this.onRelateInfoChange(taskid, "projectids", toJS(arg[2]))
                                }}
                                valueArray={projectDatas}
                            />,
                            store: taskDetailRelateProjectBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />
                <FoldList
                    sticky={needSticky}
                    data={fileFoldlistDatas}
                    showseq={false}
                    headColor={"#CD5C5C"}
                    headIconclass={"enclosure-01"}
                    headIconsize={"xxs"}
                    headIconStyle={{ width: 25 }}
                    bottomBorderColor={"#eee"}
                    count={fileFoldlistDatas.length}
                    title={getLabel(22194, '相关附件')}
                    open={true}
                    onItemClick={(dataid) => { window.openDoc(dataid, taskid, "2") }}
                    itemBottomOffset={0}
                    addIconIsUploader={true}
                    uploader={
                        {
                            com: <Upload
                                store={taskDetailRelateFileBrowserStore}
                                // datas={relateAttachment}
                                title={""}
                                multiSelection={false}
                                uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                                editable={false}
                                viewAttr={"2"}
                                onChange={(ids, datas) => { this.onUploadDatasChange(datas) }}
                                maxUploadSize={maxUploadSize}
                                // maxFilesNumber={ 16 }
                                // totalMaxUploadSize={ 300 }
                                showUploader={true}
                                showUploadTime={true}
                            />,
                            store: taskDetailRelateFileBrowserStore
                        }
                    }
                    hasRight={detail.canedit}
                />

                {
                    connectGoalsFoldListDatas.length > 0 &&
                    <FoldList
                        sticky={needSticky}
                        data={connectGoalsFoldListDatas}
                        showseq={false}
                        headColor={"#F14A2D"}
                        headIconclass={"anonymity"}
                        headIconsize={"xxs"}
                        headIconStyle={{ width: 25 }}
                        bottomBorderColor={"#eee"}
                        count={connectGoalsFoldListDatas.length}
                        title={getLabel('513887', '关联了此任务的${word}').replace('${word}', getLabel(330, '目标'))}
                        open={true}
                        onItemClick={(dataid) => { window.openAppLink(null, dataid, "wrlgoal", null, null) }}
                        itemBottomOffset={0}
                        hasRight={false}
                    />
                }
                {
                    connectTasksFoldListDatas.length > 0 &&
                    <FoldList
                        sticky={needSticky}
                        data={connectTasksFoldListDatas}
                        showseq={false}
                        headColor={"#F14A2D"}
                        headIconclass={"related-tasks"}
                        headIconsize={"xxs"}
                        headIconStyle={{ width: 25 }}
                        bottomBorderColor={"#eee"}
                        count={connectTasksFoldListDatas.length}
                        title={getLabel('513887', '关联了此任务的${word}').replace('${word}', getLabel(1332, '任务'))}
                        open={true}
                        onItemClick={(dataid) => { window.openAppLink(null, dataid, "wrltask", null, null) }}
                        itemBottomOffset={0}
                        hasRight={false}
                    />
                }
                {
                    connectPlansFoldListDatas.length > 0 &&
                    <FoldList
                        sticky={needSticky}
                        data={connectPlansFoldListDatas}
                        showseq={false}
                        headColor={"#F14A2D"}
                        headIconclass={"related-tasks"}
                        headIconsize={"xxs"}
                        headIconStyle={{ width: 25 }}
                        bottomBorderColor={"#eee"}
                        count={connectPlansFoldListDatas.length}
                        title={getLabel('513887', '关联了此任务的${word}').replace('${word}', getLabel(520530, "报告"))}
                        open={true}
                        onItemClick={(dataid) => { 
                            // window.openAppLink(null, dataid, "wrlplan", null, null) 
                            this.props.history.replace("/taskHome/taskDetail/" + taskid + "?page=2")
                            this.props.history.push("/planHome/planView/index/detail?" + dataid)
                        }}
                        itemBottomOffset={0}
                        hasRight={false}
                    />
                }
            </div>
        )
    }
}

export default Relateinfo
